import { menus } from "@/router/menu";
import svc from '@/libs/axios'
import { array_tree } from 'castle-function'
import cloneDeep from "lodash.clonedeep";
import vue from '@/main'
const state = {
    params: {}, // 数据字典
    allMenus: [], // 所有菜单，供授权使用
    menus: '', // 菜单=路由
    currentTopMenu: {}, // 当前一级菜单，默认首页
    isCollapse: false, // 侧边栏状态, sidebar:1折叠，sidebar:0展开
    isRouterAlive: true, // 当前路由是否活动可见-用于刷新
    exclude: "", // 设置不缓存组件name，逗号隔开
    routerView: true
};

const getters = {
    params: state => state.params,
    menus: state => state.menus,
    allMenus: state => state.allMenus,
    currentTopMenu: state => state.currentTopMenu,
    isCollapse: state => state.isCollapse,
    isRouterAlive: state => state.isRouterAlive,
    exclude: state => state.exclude,
};

const actions = {
    async getMenus({ commit }, payload) {
        const res = await svc.get('/user/getMenus');
        if (!res) return;
        const _import = require('@/router/import.js')

        function addComponents(data, routes = []) {
            let temp = []
            for (let x of data) {
                // if (x.children && x.children.length >= 1) {
                //     temp = temp.concat(x.children)
                // }
                if (x.isShow == 0) continue
                x.path = cloneDeep(x.href)
                let route = {
                    href: x.href,
                    path: x.path.split('?')[0],
                    component: x.path.split('?')[0] ? _import(x.path.split('?')[0]) : null,
                    name: x.name,
                    meta: {
                        parentIds: x.parentIds,
                        menuId: x.id,
                        title: x.name,
                        originTitle: x.name,
                        isDynamic: true,
                        type: x.target,
                        affix: x.affix === '1',
                        formId: x.path.split('?')[1].split('&')[1].split('=')[1]
                    },
                    query: x.path.split('?')[1],
                    icon: x.icon,
                    id: x.id,
                    pid: x.parentId
                }
                routes.push(route)
            }
            if (temp.length >= 1) {
                addComponents(temp, routes)
            }
        }
        let routes = []
        addComponents(res.data.data, routes)
        commit('setMenus', routes);
        return routes
    },
    async getParams({ commit }, payload) {
        svc.get('/user/getDicts').then(({ data }) => {
            commit('setParams', data.data)
        })
    }
};

const mutations = {
    setParams: (state, payload) => {
        state.params = payload;
    },
    setMenus: (state, data) => {
        // 没有菜单，则返回首页
        if (data.length == 0) {
            const inter = setInterval(() => {
                if (vue) {
                    clearInterval(inter);
                    vue.$router.replace('/login');
                }
            }, 500);
            return;
        }
        // 过滤与改造
        // let filterFun = (menu) => {
        //   // 如果没有传入菜单，则置空
        //   if (data.length == 0) return false;
        //   let flag = false;
        //   for (let i = 0, l = data.length; i < l; i++) {
        //     if (data[i].id == menu.id) {
        //       menu.meta.title = data[i].name;
        //       menu.title = data[i].name; // 特殊处理，供授权使用
        //       flag = true;
        //       break;
        //     }
        //   }
        //   return flag;
        // }
        // const wholeMenus = JSON.parse(JSON.stringify(data)); // 复制一个
        // // 第一层
        // let a = wholeMenus.filter(filterFun);
        // // 第二层
        // a.forEach(menu => {
        //   if (menu.children) {
        //     const c = menu.children.filter(filterFun);
        //     if (c.length) {
        //       menu.children = c;
        //     } else {
        //       delete menu.children;
        //     }
        //   }
        // })

        state.menus = data
    },
    setCurrentTopMenu: (state, payload) => {
        const path = payload
        state.currentTopMenu = state.menus ? state.menus.find(menu => menu.path === path) : '登录';
    },
    setSidebar: (state, val) => {
        sessionStorage.setItem("sidebar", val);
        state.isCollapse = val == 1 ? true : false;
    },
    // 缓存页面，提供刷新
    reload: (state) => {
        state.routerView = false
        vue.$nextTick(() => {
            state.routerView = true
        })
    },
    async logout(state, data) {
        await svc.admin_user_logout_get()
        sessionStorage.removeItem("token");
        state.menus = ''
    }
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
};